<link rel="import" href="../../bower_components/paper-material/paper-material.html">
<link rel="import" href="../../bower_components/paper-button/paper-button.html">
<link rel="import" href="../../bower_components/paper-progress/paper-progress.html">
<link rel="import" href="../../bower_components/paper-styles/typography.html">

<link rel="import" href="../app-form/app-form.html">

<dom-module id="script-add">
    <template>
        <style include="shared-styles forms single-page">
            #content {
                max-width: 900px;
            }

            paper-material {
                display: block;
                padding: 24px;
            }

            paper-progress {
                position: absolute;
                bottom: 85px;
                width: 100%;
                left: 0;
                right: 0;
            }

            :host>::slotted(paper-input-container) {
                padding-top: 16px;
                padding-bottom: 16px;
            }

            .single-head {
                @apply --script-page-head-mixin
            }
        </style>

        <div id="content">
            <paper-material class="single-head layout horizontal">
                <span class="icon">
                    <iron-icon icon="[[section.icon]]"></iron-icon>
                </span>
                <div class="title flex">
                    <h2>
                        Add Script
                    </h2>
                    <div class="subtitle">
                        You can add scripts inline or from a url.
                    </div>
                </div>
            </paper-material>
            <paper-material>
                <app-form fields="[[fields]]" form="[[script]]" url="/api/v1/scripts" on-request="_addScriptAjaxRequest" on-response="_addScriptAjaxResponse"></app-form>
            </paper-material>
        </div>


    </template>
    <script>
        Polymer({
            is: 'script-add',

            properties: {
                section: {
                    type: Object
                },
                model: {
                    type: Object
                },
                script: {
                    type: Object,
                    value: function () {
                        return {
                            name: '',
                            script: '',
                            exec_type: '',
                            entrypoint: '',
                            location_type: '',
                            description: ''
                        }
                    }
                },
                typedName: {
                    type: String,
                    value: '',
                    notify: true
                },
                fields: {
                    type: Array,
                    value: [{
                        name: "name",
                        label: "Script Name *",
                        type: "text",
                        value: "",
                        isLead: true,
                        defaultValue: "",
                        placeholder: "",
                        errorMessage: "Please enter script's name",
                        show: true,
                        required: true
                    }, {
                        name: "description",
                        label: "Script Description",
                        type: "textarea",
                        value: "",
                        defaultValue: "",
                        placeholder: "",
                        errorMessage: "Please enter script's description",
                        show: true,
                        required: false,
                        helptext: "Optional."
                    }, {
                        name: "exec_type",
                        label: "Type *",
                        type: "dropdown",
                        value: "",
                        defaultValue: "",
                        errorMessage: "Please enter script's description",
                        show: true,
                        required: true,
                        options: [{
                            title: "Executable",
                            val: "executable"
                        }, {
                            title: "Ansible Playbook",
                            val: "ansible"
                        }],
                        helptext: "Choose the type of your script. Consult the docs, on adding your scripts",
                        helpHref: "http://docs.mist.io/category/57-managing-your-scripts"
                    }, {
                        name: "location_type",
                        label: "Source *",
                        type: "dropdown",
                        value: "",
                        defaultValue: "",
                        errorMessage: "Please enter script's source",
                        show: true,
                        required: true,
                        options: [{
                            title: "Github",
                            val: "github"
                        }, {
                            title: "URL",
                            val: "url"
                        }, {
                            title: "Inline",
                            val: "inline"
                        }],
                        helptext: "Specify the type of your script source."
                    }, {
                        name: "script_url",
                        label: "Url *",
                        type: "text",
                        value: "http://",
                        defaultValue: "http://",
                        placeholder: "",
                        show: false,
                        required: true,
                        showIf: {
                            fieldName: "location_type",
                            fieldValues: ["url"]
                        },
                        errorMessage: "Please enter a url",
                        helptext: "Specify the url where the script is located."
                    }, {
                        name: "script_github",
                        label: "Github Repo *",
                        type: "text",
                        value: "",
                        defaultValue: "",
                        placeholder: "https://github.com/owner/repo",
                        show: false,
                        required: true,
                        showIf: {
                            fieldName: "location_type",
                            fieldValues: ["github"]
                        },
                        errorMessage: "Please enter a github repo",
                        helptext: "Specify the github repo where the script is located."
                    }, {
                        name: "script_inline",
                        label: "Script *",
                        type: "textarea",
                        value: "#!/bin/sh\necho \"Hello world\"",
                        class: "script",
                        defaultValue: "",
                        show: false,
                        required: true,
                        errorMessage: "Please enter inline script",
                        placeholder: "",
                        showIf: {
                            fieldName: "location_type",
                            fieldValues: ["inline"]
                        },
                        placeholderIf: {
                            fieldName: "location_type",
                            fieldOptions: {
                                "executable": "#!/bin/bash\necho 'hello world'",
                                "ansible": "- name: Dummy ansible playbook\n\thosts: localhost\n\ttasks:\n\t\t- name: Dummy task\n\t\t\tdebug:\n\t\t\t\tmsg: 'Hello World'\n"
                            }
                        },
                        helptext: "Copy paste your script. Make sure the script's format is alligned to the examples"
                    }, {
                        name: "entrypoint",
                        label: "Entry point",
                        type: "text",
                        value: "",
                        defaultValue: "",
                        placeholder: "main.yaml",
                        show: false,
                        required: false,
                        showIf: {
                            fieldName: "location_type",
                            fieldValues: ["github", "url"]
                        },
                        errorMessage: "Please enter entry point",
                        helptext: "Specify the .yml entrypoint file, otherwise 'main.yml' will be used as default."
                    }],
                    notify: true
                },
                origin: {
                    type: String
                },
                docs: {
                    type: String,
                    value: ''
                }
            },
            listeners: {
                'iron-select': 'showAppropriatePlaceholder'
            },
            ready: function () {
                if (document.querySelector('app-location')) {
                    this.set('origin', document.querySelector('app-location').queryParams.origin);
                }
                if (!this.docs)
                    for (var i=0; i < this.fields.length; i++)
                        this.fields[i].helpHref = '';
            },
            showAppropriatePlaceholder: function (e) {
                if (e.target.id == "exec_type") {
                    var type = this.fields.find(function (f) {
                        return f.name == "exec_type"
                    })
                    var placeholder = "";

                    if (type.value == "executable") {
                        placeholder = "#!/bin/bash\necho 'hello world'";
                    } else if (type.value == "ansible") {
                        placeholder =
                            "- name: Dummy ansible playbook\n  hosts: localhost\n  tasks:\n    - name: Dummy task\n      debug:\n        msg: 'Hello World'\n"
                    }
                    // placeholder does not rerender
                    // this.set('fields.6.placeholder',placeholder);
                    this.set('fields.6.value', placeholder);
                }

                if (e.target.id == "location_type") {
                    var l_type = this.fields.find(function (f) {
                        return f.name == "location_type"
                    });
                    // reset unneeded values to empty
                    if (l_type.value != "url") {
                        this.set('fields.4.value', "");
                        this.set('fields.7.value', "");
                    }
                    if (l_type.value != "github") {
                        this.set('fields.5.value', "");
                        this.set('fields.7.value', "");
                    }
                    if (l_type.value != "inline") {
                        this.set('fields.6.value', "");
                    }
                }
            },
            _addScriptAjaxRequest: function () {},
            _addScriptAjaxResponse: function (e) {
                var response = YAML.parse(e.detail.xhr.response);
                if (!this.origin) {
                    this.dispatchEvent(new CustomEvent('go-to', { bubbles: true, composed: true, detail: {
                        url: '/scripts/' + response.id
                    } }));

                } else {
                    this.dispatchEvent(new CustomEvent('update-scripts', { bubbles: true, composed: true, detail: {
                        script: response.id
                    } }));

                    history.back();
                }
            },
        });
    </script>
</dom-module>